Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Reading Stream: Byte[] vs Memory<Byte> vs Span<Byte>

What are the fundamental differences between:

var buffer = new byte[8192];
var bytesRead = Stream.Read(buffer, 0, buffer.Length);
var buffer = new byte[8192];
var span = new Span<byte>(buffer);
var bytesRead = Stream.Read(span);
var buffer = new byte[8192];
var memory = new Memory<byte>(buffer);
var bytesRead = Stream.ReadAsync(memory).Result;

Excluding the obvious fact that they are all different object types and that the only Stream.Read() method that accepts a Memory<Byte> is ReadAsync() of course.

Why would I pick any of byte[], Span<byte> or Memory<byte> over the others and how would I decide what is best for my situation?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Assuming this question is about Memory/Span/array and not Read/ReadAsync, there is no fundamental difference in this example.

The difference is that Memory/Span is an abstraction of memory, kind of like a safe pointer. They may represent a regular c# array, but might as well represent unmanaged memory. They might also represent memory of another type. So if some code loads data into a byte-array you can convert it to a int-array without doing a bunch of copying. It also supports slicing if you do not want the method to have access to all of the data.

The difference between Memory and Span is mostly that Span is more efficient, but has some restrictions in how it can be used.

So use whatever fits the data you have. If you are designing an API it is usually a good idea to take the most general type, i.e. Span/ReadonlySpan, and perhaps add overloads or extension methods for convenience.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!